/*
 *  Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 * 
 *  Licensed under the GNU General Public License v3 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.gnu.org/licenses/gpl-3.0.html
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package xperiment.metaphor.persistence.user.hibernate;

import xperiment.metaphor.persistence.hibernate.*;
import java.io.Serializable;
import org.dom4j.Element;
import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import xperiment.metaphor.model.user.User;
import xperiment.metaphor.persistence.user.UserAlreadyExistsDaoException;
import xperiment.metaphor.persistence.user.UserDao;

/**
 *
 * @author Mark Ashworth <javameme@gmail.com>
 * @version 1.0.0
 */
public class HibernateUserDao extends HibernateDao<User> implements UserDao {

    /**
     * Default constructor
     */
    public HibernateUserDao() {
        super(User.class);
    }
	
    /**
     * @deprecated Used by the old Tapestry web application, will be removed
     */
    @Override
    @Transactional(readOnly=true)
    public boolean checkLogin(String userName, String password) {
        
        try {
            Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
            Criteria criteria = session.createCriteria(User.class);
            criteria.add(Expression.ilike("name", userName));
            criteria.add(Expression.eq("password", password));
            User user = (User) criteria.uniqueResult();
            if (user != null) {
                return true;
            }
        } catch (Exception e) {
            logger.error("Unable to verify user credientials", e);
        }
        return false;
    }

    @Override
    @Transactional(readOnly=true)
	public User retrieveByName(String name) {
		
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Expression.ilike("name", name));
		return (User) criteria.uniqueResult();
	}
    
    /**
     * Persists the user. <br />
     * 
     * If the user.id is null and the username already exists
     * in the database then it is assumed that the intention is to edit the
     * user in the database with the new values in the user.<br />
     * 
     * If the user.id does not match the user.id of a user entry with the same
     * username then a DaoException is raised stating that the user already
     * exists.
     * 
     * @param object The object to persist
     * @return The persisted object
     * @throws IllegalArgumentException If the user or userName is null
     * @throws DataAccessException If there was an error persisting or loading the user from the database
     * @throws UserAlreadyExistsDaoException If the username would cause a duplicate user name
     */
    @Override
    @Transactional
	public User persist(User user) throws UserAlreadyExistsDaoException {
        if (user == null) {
            throw new IllegalArgumentException("The user is null");
        } else if (user.getUsername() == null) {
            throw new IllegalArgumentException("The user name is null");
        }
        
        User temp = retrieveByName(user.getName());
        if (user.getId() == null && temp != null) {
            user.setId(temp.getId());
        } else if (temp != null && temp.getId() != null && !user.getId().equals(temp.getId())) {
            throw new UserAlreadyExistsDaoException("The user name is already taken");
        }
        
        Serializable id = getHibernateTemplate().save(user);
        return (User) getHibernateTemplate().load(User.class, id);
	}

    @Override
    @Transactional(readOnly=false)
    public User persistXML(Element object) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Session dom4jSession = session.getSession(EntityMode.DOM4J);
        
        Serializable id = dom4jSession.save(getPersistentClass().getName(), object);
        return (User) session.get(getPersistentClass(), id);
    }
}
